package com.wxq.auth.config;

import com.wxq.common.utils.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileOutputStream;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author Jim
 * @date 1:50 下午 2022/4/12
 * @description
 * @email:huwmz04153277@126.com
 */
@ConfigurationProperties(prefix = "auth.jwt")
@Data
@Slf4j
public class JwtProperties {
    private String pubKeyPath;
    private String priKeyPath;
    private String secret;
    private String cookieName;
    private Integer expire;
    private String unick;
    private PublicKey publicKey;
    private PrivateKey privateKey;

    /**
     * 该方法早构造方法执行之后执行
     */
    @PostConstruct
    public void init(){
        try {
            File pubFile = new File(pubKeyPath);
            File priFile = new File(priKeyPath);
            System.err.println(priFile.getAbsolutePath());
            //如果公钥或者私钥不存在，重新生成
            if (!priFile.exists() || !pubFile.exists()){
                RsaUtils.generateKey(pubKeyPath,priKeyPath,secret);
            }

        } catch (Exception e){
            log.info("生成公钥和私钥出错");
            e.printStackTrace();
        }
        try {
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
        } catch (Exception e) {
            System.err.println("111");
            e.printStackTrace();
        }
        try {
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            System.err.println("222");
            e.printStackTrace();
        }
    }
}
